<?php
// +----------------------------------------------------------------------
// | CLTPHP.Pro [Admin模块中间件]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2029 https://www.cltphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://www.cltphp.com/detail-140.html )
// +----------------------------------------------------------------------
// | Author: chichu <1109305987@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\middleware;
use app\admin\model\AuthRule;
use think\Request;

class Admin
{
    use \liliuwei\think\Jump;
    public function handle($request, \Closure $next)
    {
        //获取当前用户
        $admin_id = session('admin.id');
        if (empty($admin_id)) {
            return redirect('/admin/login/index');
        }
        //定义方法白名单
        $allow = [
            'index/clear',      //清除缓存
            'index/index',      //后台首页
            'index/console',      //后台首页
            'login/index',      //登录页面
            'login/login', //校验登录
            'login/captcha',    //登录验证码
            'login/logout',     //退出登录
            'shop/getChildCate',     //获取下级分类
        ];

        //查询所有不验证的方法并放入白名单
        $authOpen = AuthRule::where('authopen','0')->select();
        $authRole = AuthRule::select();
        $authOpens = [];
        foreach ($authOpen as $k => $v) {
            //转换方法为小写
            $ruleName = explode('/', $v['url']);
            if (isset($ruleName[1]) && $ruleName[1]) {
                $ruleName[1] = strtolower($ruleName[1]);
            }
            //转换控制器首字母大写
            $ruleName = trim(implode('/', $ruleName));
            $authOpens[] = strtolower($ruleName);
            //查询所有下级权限
            $ids = getChildsRule($authRole, $v['id']);
            foreach ($ids as $kk => $vv) {
                //转换方法为小写
                $ruleName = explode('/', $vv['url']);
                if (isset($ruleName[1]) && $ruleName[1]) {
                    $ruleName[1] = strtolower($ruleName[1]);
                }
                //转换控制器首字母大写
                $ruleName = trim(implode('/', $ruleName));
                $authOpens[] = strtolower($ruleName);
            }
        }
        $allow = array_merge($allow, $authOpens);

        //查找当前控制器和方法，控制器首字母大写，方法首字母小写 如：Index/index
        $route = request()->controller(true) . '/' . lcfirst(request()->action());

        //权限认证
        if (!in_array($route, $allow)) {
            if ($admin_id != 1) {
                //开始认证
                $auth = new \Auth();
                $result = $auth->check($route, $admin_id);
                if (!$result) {
                    return $this->error('您无此操作权限','index/console');
                }
            }
        }

        //进行操作日志的记录
        \app\admin\model\AdminLog::record();

        //中间件handle方法的返回值必须是一个Response对象。
        return $next($request);
    }
}
